from django.shortcuts import render
from rest_framework.views import APIView
from .models import Areas
from rest_framework import status
from rest_framework.response import Response
from .serializers import AreaSerializer,SubsSerializer
from rest_framework.generics import ListAPIView,RetrieveAPIView
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin


# class AreasListView(ListAPIView):
#     queryset = Areas.objects.filter(parent=None)
#     serializer_class = AreaSerializer
    # def get(self, request):
    #     qs = Areas.objects.filter(parent=None)
    #     serializer = AreaSerializer(qs, many=True)
    #     return Response(serializer.data)


# class AreasDetailView(RetrieveAPIView):
#     serializer_class = SubsSerializer
#     queryset = Areas.objects.all()
    # def get(self,request,pk):
    #     '''
    #     获取单一省份下面对应的市区
    #     :param request: 请求体
    #     :param pk: 参数主键
    #     :return: 返回值
    #     '''
    #     try:
    #         #获取单一的对象
    #         qs = Areas.objects.get(pk=pk)
    #     except:
    #         return Response({'message':'无效的id'},status=status.HTTP_400_BAD_REQUEST)
    #
    #     serializer = SubsSerializer(qs)
    #     return Response(serializer.data)

class AreaViewSet(CacheResponseMixin,ReadOnlyModelViewSet):

    def get_queryset(self):
        if self.action == 'list':
            return Areas.objects.filter(parent=None)
        else:
            return Areas.objects.all()

    def get_serializer_class(self):
        if self.action == 'list':
            return AreaSerializer
        else:
            return SubsSerializer